<?php

namespace app\admin\controller;

use app\admin\model\CommonModel;
use app\admin\model\ShopCategoryModel;
use app\admin\model\ShopGoodsModel;
use app\admin\model\SpecsModel;
use app\admin\model\AttrModel;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Request;
use app\admin\model\ShopGoodsRelationModel;

//商品管理
class ShopGoodsController extends AdminBaseController
{
    //首页
    public function index(){
        $param = $this->request->param();
        $shop = new SpecsController();
        $shop_category = $shop->getShopCategory();
        $list = ShopGoodsModel
                ::where(function($query) use($param){
                    if(isset($param['title']) && !empty($param['title'])){
                        $title = $param['title'];
                        $query->where('title','like','%'.$title.'%');
                    }
                    if(isset($param['shop_id']) && $param['shop_id'] != '-1'){
                        $query->where('shop_id',$param['shop_id']);
                    }
                })
            ->field('*')
            ->order('id desc')
            ->paginate(null,false,['query'=>$param])
            ->each(function($item,$key) use($shop_category){
                $item['shop_category'] = $shop_category[$item['shop_id']];
                return $item;
            });
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);

        //搜索商城分类
        $this->assign('shop_id',$param['shop_id']??-1);
        $this->assign('shop_category',$shop_category);
        return $this->fetch();
    }

    //添加页面
    public function add(){
        //商城分类
        $shop = new SpecsController();
        $this->assign('shop_category',$shop->getShopCategory());
        //是否上架
        $shopModel = new ShopGoodsModel();
        $this->assign('is_shelf',$shopModel::IS_SHELF);
        //是否热门
        $this->assign('is_hot',$shopModel::IS_HOT);
        return $this->fetch();
    }

    //查询规格组名称以及规则属性
    public function getSpecsAttr(){
        $shop_id = $this->request->param('shop_id');
        $arr = [];
        if($shop_id == ''){
            echo json_encode($arr);exit;
        }

        $specsModel = new SpecsModel();
        $res = $specsModel
            ->field('id,specs_name')
            ->with(['attrMany'=>function($query) use($shop_id){
                $query->where('shop_id',$shop_id);
            }])
            ->where('shop_id',$shop_id)
            ->select();
        $res->hidden(['attr_many'=>['specs_id']]);//隐藏无需字段
        $arr = $res->toArray();
        echo json_encode($arr);exit;
    }

    //添加提交
    public function addPost(Request $request,ShopGoodsModel $model,ShopGoodsRelationModel $relationModel){
        $data = $request->param();
        $result = $this->validate($data,'ShopGoods');
        if($result !== true){
            $this->error($result);
        }

        //组装商品表数据
        $commonModel = new CommonModel();
        $arr_goods = [];
        $arr_goods['title'] = $data['title'];
        $arr_goods['shop_id'] = $data['shop_id'];
        $arr_goods['sort'] = $data['sort'];
        $arr_goods['is_shelf'] = $data['is_shelf'];
        $arr_goods['is_hot'] = $data['is_hot'];
        $arr_goods['thumbnail'] = $data['thumbnail'];
        $arr_goods['is_specs'] = $data['is_specs'];
        if(isset($data['photo_urls'])){
            $arr_goods['images'] = implode(',',$data['photo_urls']);
        }
        $arr_goods['content'] = $commonModel->setPostContentAttr($data['content']);
        Db::startTrans();
        if($data['is_specs'] == ShopGoodsModel::SPECS_NO){
            //组装最小价格，库存
            $arr_goods['min_price'] = $data['price'];
            $arr_goods['min_stock'] = $data['stock'];
            $res = $model->allowField(true)->create($arr_goods);
            $res1 = 1;
        }else{
            if(empty($data['min_price'])){
                $this->error('规格样式不能为空');
            }
            //有样式编号
            $res = $model->allowField(true)->create($arr_goods);
            $shop_goods_id = $res->id;
            $arr_specs = [];
            $k = 0;
            foreach($data['min_price'] as $key=>$value){
                $k +=0;
                //组装样式
                $arr_specs[$k]['shop_goods_id'] = $shop_goods_id;
                $arr_specs[$k]['shop_id'] = $data['shop_id'];
                //规格属性
                $specs_attr = [];
                if(isset($data['specs_id'][$key]) && $data['attr_id'][$key]){
                    //合并数组
                    $field = ['specs_id','attr_id'];
                    $specs_attr = $commonModel->array_merge_more($field,$data['specs_id'][$key],$data['attr_id'][$key]);
                }
                $arr_specs[$k]['specs_attr'] = json_encode($specs_attr);
                $arr_specs[$k]['goods_coin'] = $value;
                $arr_specs[$k]['stock'] = $data['min_stock'][$key];
                $k++;
            }
            //写入规格属性关联表
            $res1 = $relationModel->allowField(true)->saveAll($arr_specs);
            //更新商品最低价格，最高库存
            $min_price = $this->getMinValue(['shop_goods_id'=>$shop_goods_id],'goods_coin');
            $min_stock = $this->getMinValue(['shop_goods_id'=>$shop_goods_id],'stock');
            $model->save(['min_price'=>$min_price,'min_stock'=>$min_stock],['id'=>$shop_goods_id]);
        }
        if($res && $res1){
            Db::commit();
            $this->success('添加成功！', url('ShopGoods/index'));
        }else{
            Db::rollback();
            $this->error('添加失败');
        }
    }

    //获取最小值
    public function getMinValue($where,$field){
        $min = Db::name('shop_goods_relation')
            ->where($where)
            ->min($field);
        return $min;
    }


    //编辑页面
    public function edit(){
        $id = $this->request->param('id');
        $goodsModel = new ShopGoodsModel();
        $res = $goodsModel
            ->with('shopRelationMany')
            ->where('id',$id)
            ->find();
        $post = $res->toArray();
        if($post){
            $post['images'] = explode(',',$post['images']);
            $commonModel = new CommonModel();
            $post['content'] = $commonModel->getPostContentAttr($post['content']);

            //查询规格组名称
            $res_specs = $this->getSpecs(['shop_id'=>$post['shop_id']]);
            foreach($post['shop_relation_many'] as &$value){
                $specs_attr = json_decode($value['specs_attr'],true);
                foreach ($specs_attr as &$s_a_value){
                    $s_a_value['specs_name'] = $res_specs[$s_a_value['specs_id']];
                    $s_a_value['attr_many'] = $commonModel->selectWhereData('attr',['shop_id'=>$post['shop_id'],'specs_id'=>$s_a_value['specs_id']],'id,attr_name');
                }
                $value['specs_attr'] = $specs_attr;
            }
        }

        $this->assign('post',$post);

        //商城分类
        $shop = new SpecsController();
        $this->assign('shop_category',$shop->getShopCategory());
        //是否上架
        $shopModel = new ShopGoodsModel();
        $this->assign('is_shelf',$shopModel::IS_SHELF);
        //是否热门
        $this->assign('is_hot',$shopModel::IS_HOT);
        return $this->fetch();
    }

    //获取规格
    public function getSpecs($where){
        $commonModel = new CommonModel();
        $res = $commonModel->selectWhereData('specs',$where,'id,specs_name');
        $arr = [];
        foreach($res as $value){
            $arr[$value['id']] = $value['specs_name'];
        }
        return $arr;
    }

    //编辑提交
    public function editPost(Request $request,ShopGoodsModel $model,ShopGoodsRelationModel $relationModel){
        $data = $request->param();
        $result = $this->validate($data,'ShopGoods');
        if($result !== true){
            $this->error($result);
        }

        //组装商品表数据
        $commonModel = new CommonModel();
        $arr_goods = [];
        $arr_goods['title'] = $data['title'];
        $arr_goods['shop_id'] = $data['shop_id'];
        $arr_goods['sort'] = $data['sort'];
        $arr_goods['is_shelf'] = $data['is_shelf'];
        $arr_goods['is_hot'] = $data['is_hot'];
        $arr_goods['thumbnail'] = $data['thumbnail'];
        $arr_goods['is_specs'] = $data['is_specs'];
        if(isset($data['photo_urls'])){
            $arr_goods['images'] = implode(',',$data['photo_urls']);
        }
        $arr_goods['content'] = $commonModel->setPostContentAttr($data['content']);

        Db::startTrans();
        if($data['is_specs'] == ShopGoodsModel::SPECS_NO){
            //组装最小价格，库存
            $arr_goods['min_price'] = $data['price'];
            $arr_goods['min_stock'] = $data['stock'];
            $res = $model->allowField(true)->save($arr_goods,['id'=>$data['id']]);
            $relationModel->where('shop_goods_id',$data['id'])->delete();
            $res1 = 1;
        }else{
            if(empty($data['min_price'])){
                $this->error('规格样式不能为空');
            }
            //有样式编号
            $res = $model->allowField(true)->save($arr_goods,['id'=>$data['id']]);
            $shop_goods_id = $data['id'];
            $arr_specs = [];
            $k = 0;
            foreach($data['min_price'] as $key=>$value){
                $k +=0;
                //组装样式
                $arr_specs[$k]['shop_goods_id'] = $shop_goods_id;
                $arr_specs[$k]['shop_id'] = $data['shop_id'];
                //规格属性
                $specs_attr = [];
                if(isset($data['specs_id'][$key]) && $data['attr_id'][$key]){
                    //合并数组
                    $field = ['specs_id','attr_id'];
                    $specs_attr = $commonModel->array_merge_more($field,$data['specs_id'][$key],$data['attr_id'][$key]);
                }
                if(isset($data['relation_id'][$key])){
                    //有relation_id，则更新,无则新增
                    $arr_specs[$k]['id'] = $data['relation_id'][$key];
                }
                $arr_specs[$k]['specs_attr'] = json_encode($specs_attr);
                $arr_specs[$k]['goods_coin'] = $value;
                $arr_specs[$k]['stock'] = $data['min_stock'][$key];
                $k++;
            }
            //写入规格属性关联表
            $res1 = $relationModel->allowField(true)->saveAll($arr_specs);

            //删除的relation_id
            if(!empty($data['del_relation_ids'])){
                $relation_ids = explode(',',trim($data['del_relation_ids'],','));
                $relationModel->whereIn('id',$relation_ids)->delete();
            }
            //更新商品最低价格，最高库存
            $min_price = $this->getMinValue(['shop_goods_id'=>$shop_goods_id],'goods_coin');
            $min_stock = $this->getMinValue(['shop_goods_id'=>$shop_goods_id],'stock');
            $model->save(['min_price'=>$min_price,'min_stock'=>$min_stock],['id'=>$shop_goods_id]);
        }
        if($res && $res1){
            Db::commit();
            $this->success('添加成功！', url('ShopGoods/index'));
        }else{
            Db::rollback();
            $this->error('添加失败');
        }
    }

    //删除
    public function delete(ShopGoodsModel $model,ShopGoodsRelationModel $relationModel){
        $id = $this->request->param('id');
        $model->where('id',$id)->delete();
        $relationModel->where('shop_goods_id',$id)->delete();
        $this->success('删除成功!');
    }
}
